package com.example.webmodule.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.example.webmodule.convert.ServiceInterfaceConvert;
import com.example.webmodule.entity.ApiPathVo;
import com.example.webmodule.entity.ServiceInfo;
import com.example.webmodule.model.ServiceInterface;

import java.util.List;

/**
 * @ClassName EY-ConvertVoUtil
 * @Description com.example.webmodule.util
 * @Author menyj
 * @Date 2025/3/20
 **/
public class ConvertVoUtil {
    public static ServiceInfo convertInstaceToServiceInfo(Instance instance) {
//        ServiceInfo serviceInfo = new ServiceInfo(
//                instance.getIp(), String.valueOf(instance.getPort()), instance.getInstanceId());
        ServiceInfo serviceInfo = ServiceInfo.builder()
                .ip(instance.getIp())
                .port(String.valueOf(instance.getPort()))
                .instanceId(instance.getInstanceId())
                .build();
        serviceInfo.setMetadata(JSON.toJSONString(instance.getMetadata()));
        serviceInfo.setServiceId(extractModuleName(instance.getInstanceId()));
        return serviceInfo;
    }

    public static List<ServiceInterface> convertServiceInfoToServiceInterfaceList(ServiceInfo serviceInfo) {
        List<ServiceInterface> serviceInterfaceList = Lists.newArrayList();
        for (ApiPathVo apiPathVo: serviceInfo.getOpenApiList()) {
            ServiceInterface serviceInterface = ServiceInterfaceConvert.INSTANCE.toServiceInterface(serviceInfo);
            serviceInterface = ServiceInterfaceConvert.INSTANCE.mergeVoToModel(apiPathVo, serviceInterface);
            serviceInterfaceList.add(serviceInterface);
        }
        return serviceInterfaceList;
    }

    public static String extractModuleName(String instanceId) {
        // 使用 "@@" 分割字符串
        String[] parts = instanceId.split("@@");
        // 返回分割后的第二个部分
        return parts.length > 1 ? parts[1] : "";
    }
}
